
<template>
  <rk-dialog :title="titleType + title"
    :visible="visible"
    :showFooter="false"
    top="0"
    width="100%"
    height="100%"
    :maskClosable="false"
    :destroyOnClose="true"
    @close="handleClose">
    <rk-grid ref="agencyEaraViewRef"
      style="height: 100%;"
      :dataUrl="dataUrl"
      title=""
      :params="areaParams"
      keyField="dataId"
      boxConfig
      :autoLoad="true"
      :editConfig="{ beforeEditMethod: () => { return editConfig } }"
      :toolbarConfig="true"
      :keepSource="true"
      :columns="columns"
      :pagerConfig="false"
      :checkboxConfig="{
              reserve: true,
            }"
      @edit-closed="handleEditClose">
      <template #toolbar_buttons
        v-if="buttonType=='edit'">
        <el-button :disabled="!editConfig"
          type="primary"
          @click="handleUserOperation('add','添加')">添加</el-button>
        <el-button type="primary"
          @click="handleUserOperation('edit')">编辑</el-button>
        <el-button type="primary"
          :disabled="!editConfig"
          @click="handleUserOperation('save','保存')">保存</el-button>
        <el-button type="primary"
          :disabled="!editConfig"
          @click="handleUserOperation('cancleEdit')">取消编辑</el-button>
        <el-button type="danger"
          :disabled="!editConfig"
          @click="handleUserOperation('delete','删除')">删除</el-button>
      </template>
      <template #rk_input_edit="{ row, column }">
        <AdTreeSelect v-model="row[column.field]"
          placeholder="请选择管辖地区"
          style="width: 250px;"
          @change="(value,lable)=>handleAdChange(value,lable,row)">
        </AdTreeSelect>
      </template>
      <template #rk_name_edit="{ row, column }">
        <el-input placeholder="用户姓名"
          class="rk_input_edit"
          clearable
          v-model="row[column.field]"></el-input>
      </template>
      <template #rk_input_number="{ row, column }">
        <template v-if="row.userId">
          <span> {{ row.phoneNumber }}</span>
        </template>
        <template v-else>
          <el-input-number placeholder="请输入手机号"
            :disabled="row.userId"
            controls-position="right"
            :min="0"
            class="rk_input_edit"
            clearable
            v-model="row[column.field]"
            @blur="testPhoneNumber(row.phoneNumber)">
          </el-input-number>
        </template>
      </template>
    </rk-grid>
  </rk-dialog>
</template>
<script setup >
import { RkConfirmBox } from '@/components/message-box/index.js'
import { useAgencyApi } from '@/api'
const  { saveAgencyRegion, saveAgencyUser, deleteAgencyRegion, deleteAgencyUser } = useAgencyApi()
import XEUtils from 'xe-utils'
const emits = defineEmits([
  'refresh'
])
const titleType = ref('编辑')
const title = ref('机构用户')
// 是否展示弹窗
const visible = ref(false)
const { appContext } = getCurrentInstance();
const globalProxy = appContext.config.globalProperties;
const areaParams = reactive({
  agencyId: undefined
})
let editTableData = ref([])
const agencyEaraViewRef = ref(null)
const editConfig = ref(false)
let dataUrl = ref('')
let columns = ref(null);
const areaColumns = ref([
  {
    field: 'adCode', title: '管辖地区', width: 300, align: 'left', editRender: { autofocus: '.el-input__inner' }, slots: { edit: 'rk_input_edit' },
    formatter: ({ row }) => {
      return row.adName
    }
  },
])
const agencyColumns = ref([
  { field: 'name', title: '机构用户名称', width: 180, align: 'left', editRender: { autofocus: '.el-input__inner' }, slots: { edit: 'rk_name_edit' } },
  { field: 'phoneNumber', title: '手机号', width: 180, align: 'center', editRender: { autofocus: '.el-input__inner' }, slots: { edit: 'rk_input_number' } },
])
const userColumns = ref([
  { field: 'name', title: '用户名称', width: 180, align: 'left', editRender: { autofocus: '.el-input__inner' }, slots: { edit: 'rk_name_edit' } },
  { field: 'phoneNumber', title: '手机号', width: 180, align: 'center', editRender: { autofocus: '.el-input__inner' }, slots: { edit: 'rk_input_number' } },
])

// 手机号正则
const PHONE_NUMBER_REG = /^[1][3,4,5,7,8,9][0-9]{9}$/
const testPhoneNumber = (number) => {
  if (number && !PHONE_NUMBER_REG.test(number)) {
    globalProxy.$message({ message: `手机号不符合规范！`, type: "warning" });
    return
  }
}
// 添加和修改用户方法
const handleUserOperation = async (type, textName) => {
  if (type === 'add') {
    let record = null
    if (tableType.value == 'area') {
      record = {
        adCode: undefined,
        adName: undefined,
      }
    } else {
      record = {
        name: undefined,
        phoneNumber: undefined
      }
    }
    const { row: newRow } = await agencyEaraViewRef.value.insertAt(record, 0)
    await agencyEaraViewRef.value.setEditCell(newRow, 'record')
  } else {
    if (type === 'save') {
      const updateRecords = agencyEaraViewRef.value.getUpdateRecords()
      editTableData.value = updateRecords
      let insertRecords = agencyEaraViewRef.value.getInsertRecords()
      for (const key in updateRecords) {
        if (Object.hasOwnProperty.call(updateRecords, key)) {
          const element = updateRecords[key];
          if (tableType.value == 'area') {
            if (XEUtils.isNull(element.adCode) || XEUtils.isUndefined(element.adCode)) {
              globalProxy.$message({ message: `请选择管辖地区`, type: "warning" });
              return
            }
          } else {
            if (XEUtils.isNull(element.name) || XEUtils.isUndefined(element.name)) {
              globalProxy.$message({ message: `请输入用户名称`, type: "warning" });
              return
            }
            if (XEUtils.isNull(element.phoneNumber) || XEUtils.isUndefined(element.phoneNumber)) {
              globalProxy.$message({ message: `请输入手机号`, type: "warning" });
              return
            }
          }
        }
      }
      for (const key in insertRecords) {
        if (Object.hasOwnProperty.call(insertRecords, key)) {
          const element = insertRecords[key];
          if (tableType.value == 'area') {
            if (XEUtils.isNull(element.adCode) || XEUtils.isUndefined(element.adCode)) {
              globalProxy.$message({ message: `请选择管辖地区`, type: "warning" });
              return
            }
          } else {
            if (XEUtils.isNull(element.name) || XEUtils.isUndefined(element.name)) {
              globalProxy.$message({ message: `请输入用户名称`, type: "warning" });
              return
            }
            if (XEUtils.isNull(element.phoneNumber) || XEUtils.isUndefined(element.phoneNumber)) {
              globalProxy.$message({ message: `请输入手机号`, type: "warning" });
              return
            }
            if (!XEUtils.isNull(element.phoneNumber) && !XEUtils.isUndefined(element.phoneNumber)) {
              if (!PHONE_NUMBER_REG.test(element.phoneNumber)) {
                globalProxy.$message({ message: `手机号不符合规范！`, type: "warning" });
                return
              }
            }
          }
        }
      }
      const records = agencyEaraViewRef.value.getTableData().tableData
      let dateList = []
      records.forEach((element) => {
        if (tableType.value == 'area') {
          dateList.push({
            agencyId: areaParams.agencyId,
            adCode: element.adCode,
          });
        } else {
          dateList.push({
            agencyId: areaParams.agencyId,
            name: element.name,
            phoneNumber: element.phoneNumber,
            sysUserId: element.sysUserId,
            userId: element.userId
          });
        }
      })
      const params = dateList
      let result = null
      if (tableType.value == 'area') {
        result = await saveAgencyRegion(params)
      } else {
        result = await saveAgencyUser(params)
      }
      const { data, code, msg } = result
      if (code === 200) {
        globalProxy.$message({ message: `${textName}成功！`, type: "success" });
        handleConfirm()
      } else {
        globalProxy.$message({ message: `${msg}`, type: "error" });
      }
    } else if (type === 'edit') {
      editConfig.value = true
    } else if (type === 'cancleEdit') {
      editConfig.value = false
      let insertRecords = agencyEaraViewRef.value.getInsertRecords()
      if (insertRecords && insertRecords.length > 0) {
        agencyEaraViewRef.value.remove(insertRecords)
      }
    }
    else if (type === 'delete') {
      const seleRows = agencyEaraViewRef.value.getCheckboxRecords()
      if (seleRows.length == 0 || !seleRows) {
        globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
        return;
      }
      RkConfirmBox({
        title: '提示',
        content: `您确定要${textName}吗？`,
        onSubmit: async function () {
          //删除行
          agencyEaraViewRef.value.removeCheckboxRow()
          const removeRecords = agencyEaraViewRef.value.getRemoveRecords()
          if (removeRecords.length > 0) {
            // 获取选中数据
            const dataIdList = []
            removeRecords.forEach(element => {
              if (tableType.value == 'area') {
                dataIdList.push({
                  adCode: element.adCode,
                  agencyId: areaParams.agencyId
                })
              }
              else {
                dataIdList.push(element.userId)
              }
            });
            let params = null
            let result = null
            if (tableType.value == 'area') {
              params = dataIdList
              result = await deleteAgencyRegion(params)
            } else {
              const userIds = dataIdList.join(",");
              params = { userIds }
              result = await deleteAgencyUser(params)
            }
            const { data, code, msg } = result
            if (code === 200) {
              globalProxy.$message({ message: `${textName}成功！`, type: "success" });
              handleConfirm()
            } else {
              globalProxy.$message({ message: `${msg}`, type: "error" });
            }
          }
        },
        onCancel: function () {
        }
      })
    } else {
    }
  }
}
// 选择区划
const handleAdChange = (value, label, row) => {
  row.adName = label
}
//编辑关闭
const handleEditClose = ({ column }) => {
  const updateRecords = agencyEaraViewRef.value.getUpdateRecords()
  editTableData.value = updateRecords
}

/**
 * 打开弹窗
 * @param {Object} config 配置信息
 */
let tableType = ref('')
let buttonType = ref('')
const handleOpen = async (type, { ...config }, dialogType) => {
  visible.value = true
  buttonType.value = dialogType
  dialogType == 'edit' ? titleType.value = '编辑' : titleType.value = '查看'
  const { agencyId } = config
  tableType.value = type
  if (type == 'agency') {
    title.value = '机构用户'
    dataUrl = '/thirdAgency/getUserListByAgencyId'
    columns = agencyColumns
  } else if (type == 'area') {
    title.value = '管辖地区'
    dataUrl = '/thirdAgency/getRegionListByAgencyId'
    columns = areaColumns
  } else {
    title.value = '用户'
    dataUrl = '/thirdAgency/getUserListByAgencyId'
    columns = userColumns
  }
  areaParams.agencyId = agencyId
}
/** 关闭弹窗 */
const handleClose = () => {
  editConfig.value = false
  handleReset()
}
/** 重置数据 */
const handleReset = () => {
  visible.value = false
}
/** 确定事件 */
const handleConfirm = () => {
  handleClose()
  emitRefresh()
}
// ----- emits相关调用
const emitRefresh = () => {
  emits('refresh')
}

// 对外暴露方法
defineExpose({
  handleOpen
})

</script>
  
<style lang="scss" scoped>
.w-200px {
  width: 200px;
}
</style>
  